package com.airlines.crewassignment.controller.crew;

import static com.airlines.crewassignment.constant.RuleConstant.MAX_YEAR_HOURS;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.airlines.common.Page;
import com.airlines.crewassignment.dao.AirPortMapper;
import com.airlines.crewassignment.domain.Airport;
import com.airlines.crewassignment.domain.DateTimeRange;
import com.airlines.crewassignment.domain.FlightInfo;
import com.airlines.crewassignment.domain.util.ValueForDateUtil;
import com.airlines.crewassignment.entity.ValueForDate;
import com.airlines.crewassignment.entity.crew.CrewFlightHours;
import com.airlines.crewassignment.entity.linkline.ScheduleAuthority;
import com.airlines.crewassignment.service.crew.CrewFlightExperienceService;
import com.airlines.crewassignment.service.linkline.FlightInfoService;
import com.airlines.crewassignment.service.scheduleAuthority.ScheduleAuthorityService;
import com.github.pagehelper.PageInfo;

/**
 * @author xxxx
 * @date 2018/7/17
 * @company xxxx Airlines
 * @description
 */
@Controller
@RequestMapping("/crewFlightHours")
public class CrewFlightHoursController {
	private static final String PREFIX = "/flightHours";

	@Autowired
	private CrewFlightExperienceService crewFlightExperienceService;
	@Autowired
	private ScheduleAuthorityService scheduleAuthorityService;
	@Autowired
	private FlightInfoService flightInfoService;
	@Autowired
	private AirPortMapper airPortMapper;

	@RequestMapping("toListPage")
	public String toListPage(String dutyCode, Model model) {
		model.addAttribute("dutyCode", dutyCode);
		return PREFIX + "/flightHoursList";
	}

	@RequestMapping("toEditPage")
	public String toEditPage(String workcode, String month, String fullName, Model model) {
		model.addAttribute("workcode", workcode);
		model.addAttribute("month", month);
		return PREFIX + "/flightHoursEdit";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	// @RequiresPermissions("crewFlightHours:list")
	public Page list(String fullName, String dutyCode, Integer year, Integer offset, Integer limit)
			throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date start = sdf.parse(year + "-01-01"); // 年初
		Date end = sdf.parse(year + "-12-31"); // 年末
		DateTimeRange dateTimeRange = new DateTimeRange(start, end);

		List<CrewFlightHours> resultList = new ArrayList<>();
		// 1.人循环
		ScheduleAuthority param = new ScheduleAuthority();
		param.setDutyCode(dutyCode);
		param.setFullName(fullName);

		Page page = new Page();
		page.setPageNumber((offset / limit));
		page.setPageSize(limit);
		Page personPage = scheduleAuthorityService.listData(param, page); // 通过page获取10个人
		List<ScheduleAuthority> personList = personPage.getRows();

		List<FlightInfo> allFlightInfoList = crewFlightExperienceService.listFlightInfoForCrew(dateTimeRange, null,
				dutyCode); // 获取这一年的所有航班
		//
		if (personList != null && personList.size() > 0) {
			for (ScheduleAuthority person : personList) { // 遍历每个人

				// 2.获取当前人的航班
				List<FlightInfo> flightInfoList = flightInfoService.getFlightInfoByWorkcode(allFlightInfoList,
						person.getWorkcode());
				// 3.放入valueForDates用于通过月份分组
				List<ValueForDate> valueForDateList = new ArrayList<>();
				if (flightInfoList != null && flightInfoList.size() > 0) {
					for (FlightInfo flightInfo : flightInfoList) {
						ValueForDate temp = new ValueForDate(flightInfo.getFlightDate(),
								flightInfo.getFlightDuration());
						valueForDateList.add(temp);
					}
				}
				// 通过月份分组并相加
				List<ValueForDate> resultOfPerson = ValueForDateUtil.groupByMonth(valueForDateList); // 每人月度飞行小时
				CrewFlightHours result = new CrewFlightHours();
				result.setWorkcode(person.getWorkcode());
				result.setFullName(person.getFullName());
				result.setScheduling(person.getZTechName()); // 排班授权
				result.setMaxMonthHours(person.getLimitOfMonth()); // 月飞限制
				result.setDeptName(person.getDeptName()); // 部门
				result.setMaxYearHours(MAX_YEAR_HOURS); // 年飞限制 900
				result.setUsedYearHours(0.0); // 年度飞行小时初始化为0
				if (resultOfPerson != null && resultOfPerson.size() > 0) {
					result.setUsedMonthHours(resultOfPerson);
					Double totalOfYear = 0.0;
					for (ValueForDate vfd : resultOfPerson) {
						totalOfYear += vfd.getValue();
					}
					result.setUsedYearHours(totalOfYear / 60); // 每人年度飞行小时
				}
				resultList.add(result);
			}
		}
		PageInfo<CrewFlightHours> pageInfo = new PageInfo<CrewFlightHours>(resultList);
		personPage.setRows(pageInfo.getList());
		return personPage;
	}

	/**
	 * 获取员工每月飞行详情
	 * 
	 * @param workcode
	 * @param month
	 * @return
	 */
	@RequestMapping(value = "/listItems")
	@ResponseBody
	public List<FlightInfo> listItems(String workcode, String month, Model model) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, Integer.parseInt(month.substring(0, 4)));
		calendar.set(Calendar.MONTH, Integer.parseInt(month.substring(4, 6)) - 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		Date start = calendar.getTime(); // 月初
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DAY_OF_MONTH, 0);
		Date end = calendar.getTime(); // 月末
		DateTimeRange dateTimeRange = new DateTimeRange(start, end);

		List<FlightInfo> allFlightInfoList = crewFlightExperienceService.listFlightInfoForCrew(dateTimeRange, workcode,
				null);
		List<Airport> airportList = airPortMapper.listAllAirport();
		if (allFlightInfoList != null && allFlightInfoList.size() > 0) {
			for (FlightInfo info : allFlightInfoList) {
				for (Airport airport : airportList) {
					if (info.getDepartureAirport().equals(airport.getAirport4Code())) {
						info.setDepartureAirport(airport.getCityCnName());
					}
					if (info.getArrivalAirport().equals(airport.getAirport4Code())) {
						info.setArrivalAirport(airport.getCityCnName());
					}
				}
			}
		}

		return allFlightInfoList;
	}
}
